package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpService empService;

    @Override
    public PageResult<Clazz> getPageResult(ClazzQueryParam param) {
        Page<Clazz> page = Page.of(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));//以修改时间排序

//        //构建一个Wrapper对象
//        LambdaQueryWrapper<Clazz> queryWrapper =  new LambdaQueryWrapper<>();
//        //条件:判断传过来的param中有没有name属性,不为空,说明有值,   将条件插入like中第一个参数(条件)
//        queryWrapper.like(param.getName() != null && !param.getName().isEmpty(), Clazz::getName, param.getName())
//                .ge(param.getBegin() != null && param.getEnd() != null, Clazz::getBeginDate, param.getBegin())
//                .le(param.getBegin() != null && param.getEnd() != null, Clazz::getEndDate, param.getEnd());
//
//        page = page(page, queryWrapper);//调用service层的page方法

        page = lambdaQuery().like(param.getName() != null && !param.getName().isEmpty(), Clazz::getName, param.getName())
                .ge(param.getBegin() != null && param.getEnd() != null, Clazz::getBeginDate, param.getBegin())
                .le(param.getBegin() != null && param.getEnd() != null, Clazz::getEndDate, param.getEnd())
                .page(page);

        List<Clazz> clazzs = page.getRecords();   //获取分页后的数据
        //遍历集合，添加班主任名称
        clazzs.forEach(c -> {
            Emp emp = empService.getById(c.getMasterId());
            if (emp != null && !emp.getName().isEmpty()){
                c.setMasterName(emp.getName());
            }
            if (c.getBeginDate().isAfter(LocalDate.now())){
                c.setStatus("未开班");
            }else if (c.getEndDate().isBefore(LocalDate.now())){
                c.setStatus("已结课");
            }else {
                c.setStatus("在读");
            }
        });

        return new PageResult<>(page.getTotal(), clazzs);//封装分页数据
    }
}
